package com.gosling.gosling.leetcode;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gosling.cloudspace.common.service.UserInfoService;
import com.gosling.cloudspace.tools.DateTool;
import com.gosling.cloudspace.tools.RegexTool;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.util.stream.Stream;

@SpringBootTest
class LeetCodeTest {

    private static final Pattern IS_INTEGER_PATTERN = Pattern.compile("^[-\\+]?[\\d]*$");
    private static final Pattern MATCH_IS = Pattern.compile("/[\\x00-\\xff]/g");
    private static final String[] PAY_TYPE_CONTENTS = {"111", "112", "113", "131", "132", "141", "142"};

    @Autowired
    UserInfoService userInfoService;

    @SuppressWarnings("all")
    public static void main(String[] args) {


//        String str = "biz_content=%7B%22sub_merchant%22%3A%7B%22merchant_name%22%3A%22string%22%2C%22merchant_id%22%3A%22string%22%7D%2C%22out_trade_no%22%3A%22string%22%2C%22total_amount%22%3A%22string%22%2C%22subject%22%3A%22string%22%2C%22disable_pay_channels%22%3A%22string%22%2C%22terminal_info%22%3A%7B%22terminal_type%22%3A%22string%22%2C%22terminal_id%22%3A%22string%22%7D%2C%22area_info%22%3A%22string%22%2C%22buyer_id%22%3A%22string%22%7D";
//        str = str.replace("biz_content=","");
//        try {
//            String encode = URLDecoder.decode(str, "UTF-8");
//            System.out.println(encode);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        String str = "charset=UTF-8&method=alipay.trade.create&format=json&cert_id=4006769074&notify_url=http%3A%2F%2F182.148.123.7%3A11958%2Fali%2Fnotify.cgi&app_id=112233&sign_type=RSA2&version=1.0&timestamp=2022-04-28+18%3A07%3A43&biz_content=%7B%22sub_merchant%22%3A%7B%22merchant_name%22%3A%221234%22%2C%22merchant_id%22%3A%22112233%22%7D%2C%22out_trade_no%22%3A%2212345%22%2C%22total_amount%22%3A%2212222%22%2C%22subject%22%3A%22123%22%2C%22disable_pay_channels%22%3A%22123%22%2C%22terminal_info%22%3A%7B%22terminal_type%22%3A%22123%22%2C%22terminal_id%22%3A%22123%22%7D%2C%22area_info%22%3A%22qwer%22%2C%22buyer_id%22%3A%22123%22%7D";
//        str = str.replace("biz_content=","");
        try {
            String encode = URLDecoder.decode(str, "UTF-8");
            Map<String, String> map = qrCodeParamBuild(str);
            String object = JSONObject.toJSONString(map);
            System.out.println(encode);
            System.out.println(object);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, String> qrCodeParamBuild(String requestParam) {
        Map<String, String> reqData = null;
        try {
            String[] requestParamList = requestParam.split("&");
            reqData = new HashMap<>(8);
            for (String param : requestParamList) {
                String[] split = param.split("=");
                if (split.length == 2){
                    reqData.put(split[0], split[1]);
                } else {
                    reqData.put(split[0], "");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            reqData = new HashMap<>(8);
        }
        return reqData;
    }

    public static String getRequestParamString(Map<String, String> requestParam) {
        StringBuffer sf = new StringBuffer();
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey() + "=" + (null == en.getValue() || "".equals(en.getValue()) ? "" : en.getValue()) + "&");
                } catch (Exception e) {
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        return reqstr;
    }

    private static void mapIsNull() {
        Map map = null;
        //java.lang.NullPointerException
        boolean empty = map.isEmpty();
        System.out.println(empty);
    }

    private static void setPwd() {
        try {
            //1、鉴权规则
            String userId = "J10003";
            String pwd = "123456";
            String mobile = "13896778899";
            String fixedValue = "00000000";
            String timestamp = DateTool.getThreeMmDdHhMmSs();
            StringBuilder builder = new StringBuilder();
            builder.append(userId).append(fixedValue).append(pwd).append(timestamp);
            //待加密字符串
            String xSign = builder.toString();
            System.out.println(xSign);
            //md5加密结果
            String md5Hex = DigestUtils.md5Hex(xSign);
            System.out.println(md5Hex);
            //2、短信内容编码
            String content = "验证码：6666，打死都不要告诉别人哦！";
            String sendContent = URLEncoder.encode(content, "UTF-8");
            //转全小写
            String toLowerCase = sendContent.toLowerCase();
            System.out.println(toLowerCase);
            //3、请求参数转JSON
            HashMap requestMap = new HashMap() {{
                put("userId", userId);
                put("pwd", pwd);
                put("mobile", mobile);
                put("timestamp", timestamp);
            }};
            String requestJson = JSON.toJSONString(requestMap);
            System.out.println(requestJson);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            //
        }
    }

    private static void bitOperation() {
        //int i = 1024 >>> 8; 4
        int i = 1024 >>> 8;
        int k = 1024 >> 1;
        int J = 1024 << 1;
        System.out.println(i);
        System.out.println(k);
        System.out.println(J);
        //0XFF
        String STR_0XFF = "00000000 00000000 00000000 11111111";
    }

    private static int res(int month, int total, int count) {
        for (int i = 1; i <= month; i++) {
            if (i % 3 == 0) {
                int temp = 1;
                for (int j = month - i; j <= month; j++) {
                    temp++;
                    total += temp;
                    System.out.println(total);
                }
            }
            System.out.println(total);
        }
        return total;
    }

    /***
     * 1.有一对兔子，从出生后的第 3 个月起每个月都生一对兔子。
     * 小兔子长到第 3 个月后每个月又生一对兔子，
     * 假设所有的兔子都不死，问 30 个月内每个月的兔子总数为多少？
     * @param month
     * @return
     */
    private static int getCount(int month) {
        //1 1 2 3 5 8 13
        int total = 1;
        int count = 0;
        int temp;
        for (int i = 1; i < month; i++) {
            temp = total;
            total = total + count;
            count = temp;
            System.out.println(count);
        }
        return total;
    }

    public static int reverse(int x) {
        if (x == 0 || (x < 0 && -x < 0)) {
            return 0;
        }
        char[] chars;
        char[] chars1;
        Long result;
        if (x > 0) {
            String xStr = String.valueOf(x);
            chars = xStr.toCharArray();
            chars1 = xStr.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (i > chars.length / 2 - 1) {
                    break;
                }
                chars[i] = chars[chars.length - 1 - i];
                chars[chars.length - 1 - i] = chars1[i];
            }
            String valueOf = String.valueOf(chars);
            result = Long.valueOf(valueOf);
        } else {
            String xStr = String.valueOf(x).replace("-", "");
            chars = xStr.toCharArray();
            chars1 = xStr.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (i > chars.length / 2 - 1) {
                    break;
                }
                chars[i] = chars[chars.length - 1 - i];
                chars[chars.length - 1 - i] = chars1[i];
            }
            result = Long.valueOf("-" + String.valueOf(chars));
        }
        if (result < -2147483648 || result > 2147483647) {
            return 0;
        }
        return result.intValue();
    }

    public static int singleNumber(int[] nums) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(nums[i])) {
                int parseInt = Integer.parseInt(String.valueOf(hashMap.get(nums[i])));
                hashMap.put(nums[i], ++parseInt);
            } else {
                hashMap.put(nums[i], 1);
            }
        }
        AtomicInteger result = new AtomicInteger();
        hashMap.forEach((k, v) -> {
            if (v == 1) {
                result.set(k);
            }
        });
        return result.get();
    }

    public static boolean isPalindrome(int x) {
        //输入：x = 121
        //输出：true
        if (x < 0 || x > 2147483647) {
            return false;
        }
        String xStr = String.valueOf(x);
        char[] chars = xStr.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (!(chars[i] == chars[chars.length - 1 - i])) {
                return false;
            }
        }
        return true;
    }

    public static int[] twoSum(int[] nums, int target) {
        //输入：nums = [2,7,11,15], target = 9
        //输出：[0,1]
        //解释：因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。
        int[] result = {};
        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    System.out.println("[" + i + "]:" + "[" + j + "]");
                    result = new int[]{i, j};
                }
            }
        }
        return result;
    }

    private static void time2() {
        String dateString = "2022/4/15 14:40";
//        Date date = DateTool.dateAtWillFormat(dateString);
        Date date = new Date();
        System.out.println(date);

        SimpleDateFormat SDF_YYYY_MM_DD = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            date = SDF_YYYY_MM_DD.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date);

        String simpleYyyyMmDd = DateTool.getTwoYyyyMmDd();
        System.out.println(simpleYyyyMmDd);
    }

    private static void sub() {
        String shortName = "qqwweerrt";

        if (shortName.length() > 8) {
            shortName = shortName.substring(0, 8);
        }
        System.out.println(shortName);
    }

    private static void objMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
    }

    private static void time() {

        final String[] tops = {"大米先生", "冒菜", "螺蛳粉", "食堂", "回家吃", "猪脚饭", "鸡公煲", "面条"};
        String top = tops[new Random().nextInt(tops.length)];
        System.out.println(top);
    }

    private static void bussType() {
        String ss = "142,141,311,412,312,123,112,113,111,114,131,121,132,122,171,162,163,161,151,173,172,164,181,314";
        String[] split = ss.split(",");

        List<String> newColl = new ArrayList<>();
        for (String type : split) {
            for (String payTypeContent : PAY_TYPE_CONTENTS) {
                if (type.equals(payTypeContent)) {
                    newColl.add(type);
                }
            }
        }

        Set<String> objects = new HashSet<>();
        for (String typeColl : newColl) {
            String bussTp = "";
            if (typeColl.equals("111") || typeColl.equals("112")) {
                bussTp = "10";
            } else if (typeColl.equals("113")) {
                bussTp = "11";
            } else if (typeColl.equals("131") || typeColl.equals("132") || typeColl.equals("141") || typeColl.equals("142")) {
                bussTp = "16";
            }
            objects.add(bussTp);
        }
        for (String object : objects) {
            System.out.println(object);
        }
    }

    private static void yyyyMMdd() {
        String str = "20210504           ";
        String trim = str.trim();
        if (RegexTool.isDigits(trim)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = null;
            try {
                date = sdf.parse(trim);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String formatDate = DateUtil.formatDate(date);
            DateTime dateTime = DateUtil.parseDate(formatDate);
            System.out.println(dateTime);

        }
    }

    private static void datesss() {
        String merchantInfoUpdateTime = "2022-04-08 15:24:40";
        DateTime dateTime = DateUtil.parseDate(merchantInfoUpdateTime);
        LocalDate today = LocalDate.now();
        int year = dateTime.year();
        int month = dateTime.month() + 1;
        int dayOfMonth = dateTime.dayOfMonth();
        LocalDate oldDate = LocalDate.of(year, month, dayOfMonth);
        //更新时间和当前时间差
        Period p = Period.between(oldDate, today);
        int years = p.getYears();
        int months = p.getMonths();
        int days = p.getDays();

        System.out.printf("目标日期距离今天的时间差：%d 年 %d 个月 %d 天\n", years, months, days);
    }

    public static int length(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < value.length(); i++) {
            /* 获取一个字符 */
            String temp = value.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(chinese)) {
                /* 中文字符长度为2 */
                valueLength += 2;
            } else {
                /* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    private static int streamFor() {
        List<String> list = new ArrayList<String>();
        list.add("qq");
        list.add("11");
        list.add("11");
        list.add("11");
        list.add("11");
        list.add("11");
        list.add("qq");
        list.add("qq");
        Stream<String> stream = list.stream();
        stream.forEach(s -> {
            System.out.println(s);
            if (s.equals("qq")) {
                return;
            } else if (s.equals("11")) {
                return;
            }
        });

        return 0;
    }
}
